package com.easysoft.framework;

import com.easysoft.framework.role.model.SysRoleView;
import com.easysoft.framework.role.service.RoleService;
import com.easysoft.framework.user.model.SysUser;
import com.easysoft.framework.user.model.SysUserView;
import com.easysoft.framework.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by EasySoft on 2017/6/15.
 */
public class CustomUserRealm extends AuthorizingRealm {
    @Resource
    @Qualifier("service.UserService")
    private UserService userService;

    @Resource
    @Qualifier("service.SysRoleService")
    private RoleService roleService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String name = (String) principals.getPrimaryPrincipal();
        SysUser user = userService.selectUserByUserName(name);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<SysRoleView> userRoles = roleService.selectSysRoleByUserId(user.getId());
        List<String> roles = new ArrayList<>();
        for (SysRoleView roleView : userRoles){
            roles.add(roleView.getRoleName());
        }
        info.addRoles(roles);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String name = (String) token.getPrincipal();
        SysUserView user = userService.selectUserByUserName(name);
        if (user == null) {
            throw new UnknownAccountException();
        }
        String pwd = new String((char[]) token.getCredentials());
        String rePwd = DigestUtils.md5DigestAsHex((pwd + user.getSalt()).getBytes());
        if (!rePwd.equals(user.getPassword())) {
            throw new IncorrectCredentialsException();
        }

        return new SimpleAuthenticationInfo(name, pwd, getName());
    }
}